package com.daxue.localclient.config;

import com.daxue.grpc.lib.SimpleGrpc;
import com.daxue.grpc.lib.UserGrpc;
import com.daxue.localclient.interceptor.LogGrpcInterceptor;
import io.grpc.ClientInterceptor;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.nameresolver.DiscoveryClientResolverFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

/**
 * @author daxue0929
 * @date 2022/08/31
 **/
@Slf4j
@Order(Ordered.LOWEST_PRECEDENCE + 1)
@Configuration
public class GlobalGrpcConfiguration {

    private final DiscoveryClient discoveryClient;

    /**
     * 参考链接
     * https://blog.csdn.net/qq_31279701/article/details/127634403
     * https://blog.csdn.net/qq_27269301/article/details/120318618
     */

    @Autowired
    public GlobalGrpcConfiguration(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    @Bean
//    @GrpcGlobalClientInterceptor
    ClientInterceptor logClientInterceptor() {
        return new LogGrpcInterceptor();
    }

    @Bean
    public ManagedChannel channel() {
        return ManagedChannelBuilder.forTarget("spring-boot-grpc-server")
//            .defaultLoadBalancingPolicy("round-robin")
            .nameResolverFactory(new DiscoveryClientResolverFactory(discoveryClient))
            .intercept(new LogGrpcInterceptor())
            .usePlaintext()
            .build();
    }

    @Bean
    SimpleGrpc.SimpleBlockingStub simpleBlockingStub() {
        return SimpleGrpc.newBlockingStub(channel());
    }

    @Bean
    public UserGrpc.UserBlockingStub userBlockingStub() {
        return UserGrpc.newBlockingStub(channel());
    }

}
